<script setup>
  import { onMounted, ref } from 'vue'
  import { Box, Calendar, CircleCheck, Document, Message, Place } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { getUserListService, updateUserStatusService } from '@/api/admin.js'

  const userList = ref([])
  const isLoading = ref(true)

  // 分页相关参数
  const pagination = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })

  // 获取用户列表（带分页）
  const getUserList = async () => {
    isLoading.value = true
    try {
      const res = await getUserListService({
        current: pagination.value.currentPage,
        size: pagination.value.pageSize
      })

      // 更新总条数
      userList.value = res.data.records
      pagination.value.total = res.data.total
    } catch (err) {
      console.error(err)
    } finally {
      isLoading.value = false
    }
  }

  // 修改用户状态（启用/禁用）
  const handleUpdateUserStatus = async (userId, status) => {
    try {
      await updateUserStatusService(userId, status)
      ElMessage.success('修改成功')
      await getUserList()
    } catch (error) {
      console.error(error)
    }
  }

  // 确认修改用户状态
  const handleStatusConfirm = async user => {
    const newStatus = user.status === 0 ? 1 : 0
    const statusText = newStatus === 0 ? '启用' : '禁用'

    try {
      await ElMessageBox.confirm(`确认${statusText}用户 "${user.email}" 吗？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await handleUpdateUserStatus(user.id, newStatus)
    } catch {
      // 用户取消操作
    }
  }

  // 格式化容量显示
  const formatStorage = bytes => {
    if (bytes === 0) return '0 B'

    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))

    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  // 计算使用空间百分比
  const calculateUsagePercentage = (useSpace, totalSpace) => {
    if (totalSpace === 0) return 0
    return Math.round((useSpace / totalSpace) * 100)
  }

  // 处理页码变化
  const handleCurrentChange = page => {
    pagination.value.currentPage = page
    getUserList()
  }

  // 处理每页条数变化
  const handleSizeChange = size => {
    pagination.value.pageSize = size
    pagination.value.currentPage = 1 // 重置为第一页
    getUserList()
  }

  onMounted(() => {
    getUserList()
  })
</script>

<template>
  <div class="page page-admin-users">
    <el-alert :closable="false" show-icon title="用户管理" type="info"></el-alert>
    <!-- 用户列表 -->
    <el-card class="user-box no-select">
      <el-scrollbar>
        <el-table
          v-loading="isLoading"
          :data="userList"
          :row-style="{ height: '40px' }"
          element-loading-background="rgba(255, 255, 255, 0.9)"
          element-loading-text="数据加载中..."
          style="width: 100%; margin-top: 18px"
        >
          <template #empty>
            <el-empty description="暂无用户数据" />
          </template>
          <el-table-column align="center" label="用户ID" min-width="10%" prop="id">
            <template #header>
              <div style="display: flex; align-items: center">
                <el-icon style="font-size: 16px; margin-right: 5px">
                  <Document />
                </el-icon>
                <span>用户ID</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="邮箱" min-width="20%" prop="email">
            <template #header>
              <div class="my-column">
                <el-icon style="font-size: 16px; margin-right: 5px">
                  <Message />
                </el-icon>
                <span>邮箱</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="注册时间" min-width="15%" prop="registerTime">
            <template #header>
              <div class="my-column">
                <el-icon style="font-size: 16px; margin-right: 5px">
                  <Calendar />
                </el-icon>
                <span>注册时间</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="空间使用情况" min-width="20%">
            <template #header>
              <div class="my-column">
                <el-icon style="font-size: 16px; margin-right: 5px">
                  <Box />
                </el-icon>
                <span>空间使用情况</span>
              </div>
            </template>
            <template #default="scope">
              <div style="display: flex; flex-direction: column; align-items: center">
                <el-progress
                  :format="
                    () =>
                      `${formatStorage(scope.row.useSpace)} / ${formatStorage(scope.row.totalSpace)}`
                  "
                  :percentage="calculateUsagePercentage(scope.row.useSpace, scope.row.totalSpace)"
                  :stroke-width="10"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="角色" min-width="10%" prop="role">
            <template #header>
              <div class="my-column">
                <el-icon style="font-size: 16px; margin-right: 5px">
                  <Place />
                </el-icon>
                <span>角色</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="状态" min-width="10%" prop="status">
            <template #header>
              <div class="my-column">
                <el-icon style="font-size: 16px; margin-right: 5px">
                  <CircleCheck />
                </el-icon>
                <span>状态</span>
              </div>
            </template>
            <template #default="scope">
              <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
                {{ scope.row.status === 0 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" min-width="15%">
            <template #default="scope">
              <el-button
                :type="scope.row.status === 0 ? 'danger' : 'success'"
                size="small"
                @click="handleStatusConfirm(scope.row)"
              >
                {{ scope.row.status === 0 ? '禁用' : '启用' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 15, 20, 30]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-scrollbar>
    </el-card>
  </div>
</template>

<style lang="less" scoped>
  .el-table {
    position: relative;
    min-height: 200px;
  }

  .page-admin-users {
    height: 100%;
  }

  .user-box {
    max-height: 620px;
    position: relative;
    margin-top: 12px;
    padding: 20px;
    flex: 1;
    background-color: #fff;
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    padding: 10px 0;
  }
</style>
